<template>
  <el-drawer size="500px" v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" :title="`${drawerProps.title}用户`">
    <el-form
      class="userForm"
      ref="userFormRef"
      label-width="140px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      v-if="drawerProps.row"
    >
      <el-form-item label="登录ID" prop="optcode">
        <el-input v-model="drawerProps.row!.optcode" placeholder="请填写登录ID" clearable></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="optname">
        <el-input v-model="drawerProps.row!.optname" placeholder="请填写名称" clearable></el-input>
      </el-form-item>
      <el-form-item class="password" label="密码" prop="password" v-if="drawerProps.title === '新增'">
        <el-input type="password" v-model="drawerProps.row!.password" placeholder="请输入密码" autocomplete="new-password">
          <template #prefix>
            <el-icon class="el-input__icon"><lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="停用">
        <el-switch
          v-model="drawerProps.row!.bstop"
          inline-prompt
          :active-icon="Check"
          :inactive-icon="Close"
          style="margin: 0 auto"
        />
      </el-form-item>
      <el-form-item label="启用部门权限">
        <el-switch
          v-model="drawerProps.row!.bdepartmentright"
          inline-prompt
          :active-icon="Check"
          :inactive-icon="Close"
          style="margin: 0 auto"
        />
      </el-form-item>
      <el-form-item label="启用地图权限">
        <el-switch
          v-model="drawerProps.row!.barearight"
          inline-prompt
          :active-icon="Check"
          :inactive-icon="Close"
          style="margin: 0 auto"
        />
      </el-form-item>
      <el-form-item label="启用门禁组权限">
        <el-switch
          v-model="drawerProps.row!.brulegroupright"
          inline-prompt
          :active-icon="Check"
          :inactive-icon="Close"
          style="margin: 0 auto"
        />
      </el-form-item>
      <el-form-item label="启用门禁点权限">
        <el-switch
          v-model="drawerProps.row!.bdoorright"
          inline-prompt
          :active-icon="Check"
          :inactive-icon="Close"
          style="margin: 0 auto"
        />
      </el-form-item>
      <el-form-item label="启用锁地图权限">
        <el-switch
          v-model="drawerProps.row!.broommapright"
          inline-prompt
          :active-icon="Check"
          :inactive-icon="Close"
          style="margin: 0 auto"
        />
      </el-form-item>
    </el-form>
    <!-- <div class="tip">注：用户默认密码与登录ID相同</div> -->
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" :loading="loading" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getRoleTree } from "@/api/modules/user";
import { Check, Close } from "@element-plus/icons-vue";
import JSEncrypt from "jsencrypt";

const loading = ref(false);
const roleList: any = ref([]);
const rules = reactive({
  optcode: [{ required: true, message: "请填写登录ID" }],
  optname: [{ required: true, message: "请填写名称" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      //插入正则验证：大小写、数字、至少6位、不常用字符
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()\-_=+{};:,<.>])[a-zA-Z][a-zA-Z0-9!@#$%^&*()\-_=+{};:,<.>]{5,17}$/,
      message: "密码6-18位(以字母开头，同时包含大写字母、小写字母、数字以及?=.*[!@#$%^&*()\-_=+{};:,<.>]特殊字符)",
      trigger: "blur"
    }
  ]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: { [key: string]: any };
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.title === "新增") {
    drawerProps.value.row = {
      optcode: "",
      optname: "",
      bstop: false,
      bdepartmentright: false,
      barearight: false,
      brulegroupright: false,
      bdoorright: false,
      broommapright: false
    };
  }
};

// 提交数据（新增/编辑）
const userFormRef = ref<FormInstance>();
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  userFormRef.value && userFormRef.value.resetFields();
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  userFormRef.value!.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    const encryptor = new JSEncrypt();
    const params = drawerProps.value.row;
    let password;
    encryptor.setPublicKey(import.meta.env.VITE_PUBLIC_kEY);
    if (drawerProps.value.title === "新增") {
      password = encryptor.encrypt(drawerProps.value.row!.password) as string;
      params.password = password;
    }
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
      loading.value = false;
    } catch (error) {
      loading.value = false;
      console.log(error);
    }
  });
};

const getRoleTreeFunc = async () => {
  try {
    const res = await getRoleTree();
    roleList.value = res.roleList;
  } catch (error) {
    console.log(error);
  }
};

onMounted(async () => {
  getRoleTreeFunc();
});
defineExpose({
  acceptParams
});
</script>
<style lang="scss" scoped>
.tip {
  padding: 10px 20px;
  font-size: 14px;
  color: #f39c12;
}
.userForm .password {
  margin-bottom: 50px;
}
</style>
